package cn.tradewin.pmp.services.download.impl;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRXlsExporter;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.services.Response;

import cn.tradewin.common.util.MimeSymbols;
import cn.tradewin.pmp.services.download.OutputStreamResponse;

public class XlsOutputStreamResponse implements OutputStreamResponse {

	private final String filename;
	private final Asset jasper;
	private final Map<String, Object> parameters;
	private final JRDataSource jrDataSource;

	public XlsOutputStreamResponse(Asset jasper,
			Map<String, Object> parameters, JRDataSource jrDataSource, String filename) {
		this.filename = filename;
		this.jasper = jasper;
		this.parameters = parameters;
		this.jrDataSource = jrDataSource;
	}

	@Override
	public String getContentType() {
		return MimeSymbols.APPLICATION_EXCEL;
	}

	@Override
	public void writeToStream(OutputStream out) throws IOException {
		try {
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasper
					.getResource().openStream(), parameters, jrDataSource);
			JRXlsExporter exporter = new JRXlsExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
			exporter.exportReport();
		} catch (JRException e) {
			StringWriter stringWriter = new StringWriter();
			PrintWriter printWriter = new PrintWriter(stringWriter);
			e.printStackTrace(printWriter);
			out.write(stringWriter.toString().getBytes());
		}
	}

	@Override
	public void prepareResponse(Response response) {
		try {
			String output = new File(filename).getName();
			// 如果不设定该header的值，就会直接在浏览器上显示的内容。
			response.setHeader("Content-Disposition", "attachment; filename=\""  + URLEncoder.encode(output, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}
